package com.traffic.fuwu.controller;

import com.traffic.fuwu.mybatis.pojo.AppVersion;
import com.traffic.fuwu.service.AppVersionService;
import com.traffic.fuwu.service.DeviceService;
import com.traffic.fuwu.util.Page;
import com.traffic.fuwu.util.ToolUtil;
import com.traffic.fuwu.vo.VoStatus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.io.FileUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by piKeWei on 2017/2/9.
 */
@Controller
@RequestMapping("/apkVersion")
public class ApkVersionController {
    private static final Logger log = LoggerFactory.getLogger(ApkVersionController.class);
    private static final VoStatus voStatus = new VoStatus();

    @Autowired
    private DeviceService deviceService;
    @Autowired
    AppVersionService appVersionService;

    /**
     * 版本升级信息多条件查询
     *
     * @param isUpdated
     * @param deviceId
     * @param companyName
     * @param companyCode
     * @param lineShort
     * @param lineName
     * @param pageIndex
     * @return
     */
    @RequestMapping("/findDeviceApk")
    @ResponseBody
    public Map<String, Object> findDeviceApk(String isUpdated, String deviceId, String companyName,
                                             String companyCode, String lineShort, String lineName, String pageIndex) {
        Map<String, Object> map = new HashMap<>();
        try {
            do {
                String pageSize = "10";// 每一页的行数
                if (StringUtils.isEmpty(pageIndex)) {
                    pageIndex = "1";
                }
                Page page = new Page();
                page.setPageIndex(Integer.parseInt(pageIndex));
                page.setPageSize(Integer.parseInt(pageSize));
                int temp = 0;
                if (StringUtils.isNotBlank(isUpdated)) {
                    temp = Integer.parseInt(isUpdated);
                }

                int count = deviceService.findDeviceApkCount(temp, deviceId, companyName, companyCode, lineShort, lineName);
                page = ToolUtil.getPage(count, page);

                List<Map<String, Object>> list = deviceService.findDeviceApk(temp, deviceId, companyName, companyCode, lineShort, lineName, page.startRow(),
                        page.getPageSize());
                if (list == null && list.size() == 0) {
                    voStatus.setCode(0);
                    voStatus.setMessage("查无数据");
                    map.put("status", voStatus);
                    break;
                }
                map.put("line", list);
                voStatus.setCode(1);
                voStatus.setMessage("查询成功");
                map.put("page", page);
                map.put("status", voStatus);
            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("版本升级信息多条件查询接口异常");
        }
        return map;
    }

    /**
     * 增加新版版
     * @param file
     * @param request
     * @param version
     * @param session
     * @param response
     * @param appKey
     * @return
     */
    @RequestMapping(value = "/addVersion")
    @ResponseBody
    public ModelAndView addVersion(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
                                   HttpServletRequest request, String version, HttpSession session, HttpServletResponse response,
                                   String appKey) {
        Map<String, Object> map = new HashMap<>();
        ModelAndView mv = new ModelAndView("redirect:/traffic/apk?&appKey="+appKey);
        try {
            do {
                if (file == null) {
                    voStatus.setCode(0);
                    voStatus.setMessage("上传失败，无上传文件！");
                    map.put("status", voStatus);
                    break;
                }
                String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
                String filename = file.getOriginalFilename() + type;// 获取文件名
                String path = request.getSession().getServletContext().getRealPath("/upload/" + filename);// 存放位置
                File destFile = new File(path);
                FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下

                AppVersion appVersion = new AppVersion();

                appVersion.setVersionDesc(version + "号版本");
                appVersion.setPackagePath(filename);
                appVersion.setAppKey(appKey);
                appVersion.setCreateTime(new Date());
                appVersionService.addVersion(appVersion);

                voStatus.setCode(1);
                voStatus.setMessage("上传成功");
                map.put("status", voStatus);

            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mv.addObject("result",map);
        return mv;
    }

    /**
     * apk升级首页
     *
     * @param request
     * @return
     */
    @RequestMapping("/apk/index")
    @ResponseBody
    public ModelAndView apkIndex(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        ModelAndView mv = new ModelAndView();
        try {
            String isUpdated = request.getParameter("");
            String deviceId = request.getParameter("");
            String companyName = request.getParameter("");
            String companyCode = request.getParameter("");
            String lineShort = request.getParameter("");
            String lineName = request.getParameter("");
            String pageIndex = request.getParameter("");
            do {
                String pageSize = "10";// 每一页的行数
                if (StringUtils.isEmpty(pageIndex)) {
                    pageIndex = "1";
                }
                Page page = new Page();
                page.setPageIndex(Integer.parseInt(pageIndex));
                page.setPageSize(Integer.parseInt(pageSize));
                int temp = 0;
                if (StringUtils.isNotBlank(isUpdated)) {
                    temp = Integer.parseInt(isUpdated);
                }

                int count = deviceService.findDeviceApkCount(temp, deviceId, companyName, companyCode, lineShort, lineName);
                page = ToolUtil.getPage(count, page);

                List<Map<String, Object>> list = deviceService.findDeviceApk(temp, deviceId, companyName, companyCode, lineShort, lineName, page.startRow(),
                        page.getPageSize());
                if (list == null && list.size() == 0) {
                    voStatus.setCode(0);
                    voStatus.setMessage("查无数据");
                    map.put("status", voStatus);
                    break;
                }
                map.put("line", list);
                voStatus.setCode(1);
                voStatus.setMessage("查询成功");
                map.put("page", page);
                map.put("status", voStatus);
            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("版本升级信息多条件查询接口异常");
        }
        mv.addObject("result", map);
        mv.setViewName("/apk/index");
        return mv;
    }

    /**
     * 跳转上传页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload/index")
    public ModelAndView uploadIndex(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/apk/apkUpload");
        String appKey = request.getParameter("appKey");
        mv.addObject("appKey", appKey);
        return mv;
    }

    /**
     * 修改升级信息
     * @param updateList
     * @return
     */
    @RequestMapping(value = "/updateAppUpgradeFlag")
    @ResponseBody
    public Map<String,Object> updateAppUpgradeFlag(String[] updateList){
        Map<String,Object> map = new HashMap<>();
        try {
            do {
                if (updateList == null){
                    voStatus.setCode(0 );
                    voStatus.setMessage("修改失败，无修改信息");
                    map.put("status", voStatus);
                    break;
                }
            }while (false);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
}
